package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hustcad.plm.basic.multipartfile.LocalFileMultipartFile;
import com.hustcad.plm.basic.util.TyplmEntityBaseUtil;
import com.hustcad.plm.basic.vo.cad.CadDownloadFileVO;
import com.hustcad.plm.pdm.basedrule.dto.TyplmBaseRuleBoundedObjDTO;
import com.hustcad.plm.pdm.basedrule.service.TyplmBasedRuleService;
import com.hustcad.plm.pdm.code.model.dto.codemanagement.TyplmSegmentCodeConditionDTO;
import com.hustcad.plm.pdm.code.model.vo.codemanagement.segmentcode.TyplmSegmentCodeRuleVO;
import com.hustcad.plm.pdm.code.service.codemanagement.TyplmSegmentCodeService;
import com.hustcad.plm.pdm.container.model.vo.ContainerCommonQueryVO;
import com.hustcad.plm.pdm.ec.module.dto.AffectedObjectDTO;
import com.hustcad.plm.pdm.ec.module.dto.TyplmChangeIssueDTO;
import com.hustcad.plm.pdm.ec.service.TyplmChangeIssueService;
import com.hustcad.plm.pdm.file.model.dto.BatchUploadDTO;
import com.hustcad.plm.pdm.file.model.dto.ContentUploadDTO;
import com.hustcad.plm.pdm.file.model.dto.DownloadFileDTO;
import com.hustcad.plm.pdm.file.model.vo.DownLoadFile.DownLoadFileVO;
import com.hustcad.plm.pdm.file.service.TyplmFileHandleService;
import com.hustcad.plm.pdm.file.service.upload.TyplmFileTransferService;
import com.hustcad.plm.pdm.file.util.TyplmDownloadToolUtil;
import com.hustcad.plm.pdm.filevault.service.TyplmContentDataService;
import com.hustcad.plm.pdm.filevault.service.TyplmContentReferenceLinkService;
import com.hustcad.plm.pdm.filevault.service.TyplmEncryptService;
import com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.org.OrgDO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.entity.part.PartDO;
import com.ty.basic.entity.part.PartMasterDO;
import com.ty.basic.handler.exceptionhandler.exception.ResponseCodeEnum;
import com.ty.basic.handler.exceptionhandler.exception.TyException;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.common.CommonService;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.constant.RTPlmConstant;
import cqrtplm.dto.OnlineAnnotationDTO;
import cqrtplm.dto.ProblemReportDTO;
import cqrtplm.entity.*;
import cqrtplm.info.OnlineAnnotationInfo;
import cqrtplm.mapper.*;
import cqrtplm.service.RTChangeService;
import cqrtplm.service.RTContainerAndFolderService;
import cqrtplm.util.RTFileUtil;
import cqrtplm.vo.OnlineAnnotationVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RTChangeServiceImpl implements RTChangeService {
    @Resource
    private TyplmChangeIssueService typlmChangeIssueService;
    @Resource
    private RTContainerAndFolderService containerAndFolderService;
    @Resource
    private TyplmTypeService typlmTypeService;
    @Resource
    private RTContainerAndFolderMapper containerAndFolderMapper;
    @Resource
    private TyplmBasedRuleService typlmBasedRuleService;
    @Resource
    private TyplmSegmentCodeService typlmSegmentCodeService;
    @Resource
    private RTFormTemplateMapper formTemplateMapper;
    @Resource
    private TyplmFileHandleService typlmFileHandleService;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private OnlineAnnotationMapper onlineAnnotationMapper;
    @Resource
    private TyplmContentReferenceLinkService typlmContentReferenceLinkService;
    @Resource
    private TyplmFileTransferService typlmFileTransferService;
    @Resource
    private TyplmEncryptService typlmEncryptService;
    @Resource
    private TyplmContentDataService typlmContentDataService;
    @Resource
    private RtChangeaffectPartinventoryMapper rtChangeaffectPartinventoryMapper;
    @Resource
    private OnlineAnnotationLinkMapper onlineAnnotationLinkMapper;
    @Resource
    private RTChangeMapper rtChangeMapper;
    @Resource
    private RTPartMapper rtPartMapper;
    @Resource
    private TyplmPdmPartService typlmPdmPartService;
    @Resource
    private TyplmPartService typlmPartService;
    @Resource
    private TyplmFileHandleService fileHandleService;
    @Resource
    private RtChangeaffectOrderlistMapper rtChangeaffectOrderlistMapper;
    @Resource
    private RtZdMapper rtZdMapper;
    @Resource
    private RtChangeaffectFinishedbomMapper rtChangeaffectFinishedbomMapper;
    @Resource
    private RtChangeaffectAppointMapper rtChangeaffectAppointMapper;
    @Resource
    private RtChangeaffectMbomMapper rtChangeaffectMbomMapper;
    @Resource
    private RtChangeaffectAssociatedbomMapper rtChangeaffectAssociatedbomMapper;
    @Resource
    private RtChangeLockInfoMapper rtChangeLockInfoMapper;
    @Value("${file.default.dir}")
    private String fileExportDefaultDir;
    @Resource
    private CommonService commonService;
    //库存查询接口
    @Value("${sap.queryInventory.username}")
    private String queryInventoryUsername;
    @Value("${sap.queryInventory.password}")
    private String queryInventoryPassword;
    @Value("${sap.queryInventory.url}")
    private String queryInventoryUrl;
    //订单查询接口
    @Value("${sap.queryOrderList.username}")
    private String queryOrderListUsername;
    @Value("${sap.queryOrderList.password}")
    private String queryOrderListPassword;
    @Value("${sap.queryOrderList.url}")
    private String queryOrderListUrl;
    //成品码允许下单状态
    @Value("${product.unlock.status}")
    private String productUnlockStatus;
    //工厂视图
    @Value("${factory.view}")
    private String factoryView;

    @Override
    public void createProblemReport(ProblemReportDTO dto, List<String> comment, List<MultipartFile> files) throws Exception {
        UserDO user = TyAccountContext.getUser();

        ContainerCommonQueryVO container = containerAndFolderService.getContainerByName(RTPlmConstant.PRODUCT_CONTAINER_NAME);
        BigInteger noticeTypeOid = typlmTypeService.getTypeOidByName(TableTypeConstrant.TY_CHANGEISSUE_OTYPE);
        TyplmChangeIssueDTO changeIssueDTO = new TyplmChangeIssueDTO();
        changeIssueDTO.setName(RTPlmConstant.PROBLEM_REPORT);
        BigInteger containerId = new BigInteger(container.getId());
        TyplmBaseRuleBoundedObjDTO info = this.typlmBasedRuleService.getBaseRuleBoundedObjInfo(noticeTypeOid, containerId, container.getOtype());
        TyplmSegmentCodeConditionDTO param = new TyplmSegmentCodeConditionDTO();
        param.setOtype(TableTypeConstrant.TY_CHANGEISSUE_OTYPE);
        param.setRuleInfo(new IdentifierEntity(info.getSegmentCodeOid(), info.getSegmentCodeOtype()));
        TyplmSegmentCodeRuleVO codeData = this.typlmSegmentCodeService.getSegmentFormData(param);
        if (CollUtil.isNotEmpty(files)) {
            changeIssueDTO.setFileList(files);
        }
        changeIssueDTO.setContaineroid(containerId);
        changeIssueDTO.setContainerotype(container.getOtype());
        changeIssueDTO.setSubfolderoid(containerAndFolderMapper.getOIDByNameAndContainerOid(RTPlmConstant.PROBLEM_REPORT, containerId));
        changeIssueDTO.setTypeoid(noticeTypeOid);
        changeIssueDTO.setCreatoroid(user.getOid());
        changeIssueDTO.setObjectNumber(codeData.getCode());
        changeIssueDTO.setFormtemplateoid(info.getFormTemplateOid());
        changeIssueDTO.setFormtemplateotype(info.getFormTemplateOtype());
        changeIssueDTO.setFormData(formTemplateMapper.queryTemplateDataByOid(info.getFormTemplateOid()));
        changeIssueDTO.setIssuepriority(RTPlmConstant.NORMAL);
        HashMap<String, List<String>> map = new HashMap<>();
        map.put("tzpz", Collections.singletonList(comment.toString()));
        changeIssueDTO.setIbaAttribute(map);
        changeIssueDTO.setIssueAgainstDataList(Collections.singletonList(new AffectedObjectDTO(new BigInteger(dto.getObjId()), dto.getObjType(), "")));
        typlmChangeIssueService.createChangeIssue(changeIssueDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void uploadOnlineAnnotationFile(OnlineAnnotationDTO dto) {
        OnlineAnnotationLinkDO onlineAnnotationLinkDO = new OnlineAnnotationLinkDO();
        String flag = dto.getFlag();
        MultipartFile multipartFile;
        File file = null;
        try {
            if ("img".equals(flag)) {
                String filePath = String.valueOf(Paths.get(fileExportDefaultDir, dto.getFileName() + ".png"));
                file = new File(filePath);
                String baseImg = dto.getBaseImg();
                RTFileUtil.processBase64ToFile(baseImg, filePath, file);
                onlineAnnotationLinkDO.setBase64Image(baseImg);
                multipartFile = new LocalFileMultipartFile(file, "application/octet-stream", file.getName(), file.getName());
                OnlineAnnotationLinkDO onlineAnnotationLink = onlineAnnotationLinkMapper.selectByBoid(dto.getOid());
                if (onlineAnnotationLink != null) {
                    onlineAnnotationLink.setBase64Image(baseImg);
                    TyplmEntityBaseUtil.fillCommonFieldForUpdate(onlineAnnotationLinkDO);
                    onlineAnnotationLinkMapper.updateByPrimaryKey(onlineAnnotationLink);
                    return;
                }

            } else {
                multipartFile = dto.getFile();
            }
            String value = simpleUploadFile(Collections.singletonList(multipartFile));
            onlineAnnotationLinkDO.setBoid(new BigInteger(value));
            onlineAnnotationLinkDO.setAoid(dto.getOid());
            onlineAnnotationLinkDO.setName(dto.getFileName());
            onlineAnnotationLinkDO.setRemark(dto.getFlag());
            onlineAnnotationLinkDO.setOid(snowflakeIdComponent.getInstance().nextId());
            TyplmEntityBaseUtil.fillCommonFieldForCreate(onlineAnnotationLinkDO);
            onlineAnnotationLinkMapper.insert(onlineAnnotationLinkDO);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if ("img".equals(flag)) {
                file.delete();
            }
        }
    }

    /**
     * 文件上传
     *
     * @param files
     * @return
     */
    private String simpleUploadFile(List<MultipartFile> files) {
        List<ImmutablePair<String, IdentifierEntity>> list = typlmFileHandleService.batchSimpleUploadFile(files);
        if (CollUtil.size(list) != CollUtil.size(files)) {
            TyException.throwSingleTyExceptionVarargs(ResponseCodeEnum.BIZ_UPLOAD_FILE_FAILD);
        }
        List<IdentifierEntity> entityList = list.stream().map(ImmutablePair::getRight).collect(Collectors.toList());
        return String.valueOf(entityList.get(0).getOid());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createProblemReportByAnnotation(List<String> list) throws Exception {
        for (String guid : list) {
            List<OnlineAnnotationInfo> vos = onlineAnnotationMapper.selectByFileInfoByGuid(guid);
            if (CollUtil.isEmpty(vos)) {
                return;
            }
            List<BigInteger> fileIds = vos.stream()
                    .map(OnlineAnnotationInfo::getFileID)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            List<String> descriptions = Collections.singletonList(vos.get(0).getDescription());
            List<MultipartFile> fileList = new ArrayList<>();
            if (CollUtil.isNotEmpty(fileIds)) {
                fileIds.addAll(this.typlmContentReferenceLinkService.queryFileIlluStrationFileOids(fileIds));
                List<CadDownloadFileVO> cadDownloadFileVOList = this.typlmFileTransferService.getDownloadFileDTOS(fileIds, TyAccountContext.getUser().getOid());
                List<DownloadFileDTO> downloadFileDTOList = TyplmDownloadToolUtil.getDownloadFileDTOS(cadDownloadFileVOList);
                Iterator var7 = downloadFileDTOList.iterator();
                while (var7.hasNext()) {
                    DownloadFileDTO downloadFileDTO = (DownloadFileDTO) var7.next();
                    this.typlmEncryptService.recordFileNameKeys(new BigInteger(downloadFileDTO.getFileId()));
                    DownLoadFileVO downLoadFileVO = this.typlmContentDataService.getInputStream(downloadFileDTO);
                    File file = downLoadFileVO.getFile();
                    String fileName = downLoadFileVO.getFileName();
                    InputStream entryStream = FileUtils.openInputStream(file);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    FileCopyUtils.copy(entryStream, baos);
                    MultipartFile multipartFile = new MockMultipartFile(fileName, fileName, "application/octet-stream", baos.toByteArray());
                    fileList.add(multipartFile);
                }
            }
            createProblemReport(new ProblemReportDTO(vos.get(0).getObjOType(), vos.get(0).getObjOid()), descriptions, fileList);
        }
    }

    @Override
    public List<OnlineAnnotationVO> selectOnlineAnnotationByOid(String aoid) {
        List<OnlineAnnotationVO> onlineAnnotationVOS = onlineAnnotationMapper.selectByAOid(aoid);
        return OnlineAnnotationVO.buildVO(onlineAnnotationVOS);
    }

    private void addSplitItemsToFileIds(Collection<BigInteger> fileIds, String input) {
        if (input == null || input.trim().isEmpty()) {
            return;
        }

        Arrays.stream(input.split(",")).map(String::trim).filter(s -> !s.isEmpty()).map(BigInteger::new).forEach(fileIds::add);
    }

    @Override
    public int deleteOnlineAnnotationFile(String oid) {
        return onlineAnnotationLinkMapper.deleteFileByBOid(oid);
    }


    /**
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public String checkBomCertPattern(LinkedHashMap<String, Object> map) throws Exception {
        if (!map.isEmpty()) {
            for (Object key : map.keySet()) {
                PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(key.toString());
                if (partDO != null) {
                    String PowerRegistrationModel = rtChangeMapper.queryIBAValueByOidAndOtype(partDO.getOid().toString(), partDO.getOtype(), "PowerRegistrationModel");
                    String CertificationRequire = rtChangeMapper.queryIBAValueByOidAndOtype(partDO.getOid().toString(), partDO.getOtype(), "CertificationRequire");

                }
            }
        }
        return "";
    }

    /**
     * 零件库存查询
     *
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public List<JSONObject> queryPartInventory(LinkedHashMap<String, Object> map) throws Exception {
        List<JSONObject> list = new ArrayList<>();
        if (!map.isEmpty()) {
            JSONObject body = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            List<String> PatternList = (List) map.get("PatternCode");
            List<String> MaterialList = (List) map.get("MaterialCode");
            if (PatternList == null) {
                PatternList = new ArrayList<>();
            }
            if (MaterialList == null) {
                MaterialList = new ArrayList<>();
            }
            String changeNo = (String) map.get("changeNo");
            if (PatternList != null && !PatternList.isEmpty()) {
                for (String pattern : PatternList) {
                    JSONObject patternObject = new JSONObject();
                    patternObject.put("MATNR", "");
                    patternObject.put("ZTH", pattern);
                    jsonArray.add(patternObject);
                }
            }
            if (MaterialList != null && !MaterialList.isEmpty()) {
                for (String material : MaterialList) {
                    JSONObject materialObject = new JSONObject();
                    materialObject.put("MATNR", material);
                    materialObject.put("ZTH", "");
                    jsonArray.add(materialObject);
                }
            }
            PatternList.addAll(MaterialList);
            if (StringUtils.isNotBlank(changeNo)) {
                for (String pattern : PatternList) {
                    List<RtChangeaffectPartinventoryDO> doList = this.rtChangeaffectPartinventoryMapper.queryByChangeNoAndPartNo(changeNo, pattern);
                    List<JSONObject> jsonList = doList.stream().map(item -> (JSONObject) JSONObject.toJSON(item)).collect(Collectors.toList());
                    list.addAll(jsonList);
                }
            }
            if (CollectionUtils.isEmpty(list)) {
                if (jsonArray.size() > 0) {
                    JSONObject bodyObject = new JSONObject();
                    bodyObject.put("item", jsonArray);
                    body.put("IN_TAB", bodyObject);
                    String queryStr = this.commonService.sendPostRequest(queryInventoryUrl, queryInventoryUsername, queryInventoryPassword, body.toString());
                    if (StringUtils.isBlank(queryStr)) {
                        throw new Exception("返回参数为空！");
                    }
                    JSONObject out = JSON.parseObject(queryStr);
                    if (out.containsKey("OUT_TAB")) {
                        JSONObject OUT_TAB = out.getJSONObject("OUT_TAB");
                        if (OUT_TAB != null && OUT_TAB.containsKey("item")) {
                            JSONArray item = OUT_TAB.getJSONArray("item");
                            for (int i = 0; i < item.size(); i++) {
                                JSONObject itemObject = item.getJSONObject(i);
                                Object WERKS = itemObject.get("WERKS");
                                Object MATNR = itemObject.get("MATNR");
                                Object PARTNER = itemObject.get("PARTNER");
                                Object BU_SORT1 = itemObject.get("BU_SORT1");
                                Object KALAB = itemObject.get("KALAB");
                                Object MENGE = itemObject.get("MENGE");
                                itemObject = new JSONObject();
                                itemObject.put("factory", WERKS);
                                String partName = "";
                                if (MATNR != null) {
                                    JSONObject part = rtChangeMapper.queryLatestMaterialByCode(MATNR.toString(), RTPlmConstant.VIEW_DESIGN);
                                    if (part != null) {
                                        partName = part.get("NAME").toString();
                                    }
                                }
                                itemObject.put("materialCode", MATNR);
                                itemObject.put("partName", partName);
                                itemObject.put("supplier", BU_SORT1);
                                itemObject.put("inPutInventory", KALAB);
                                itemObject.put("onWayInventory", MENGE);
                                list.add(itemObject);
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    /**
     * 零件库存保存
     *
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public List<JSONObject> savePartInventory(LinkedHashMap<String, Object> map) throws Exception {
        if (!map.isEmpty()) {
            UserDO user = TyAccountContext.getUser();
            String changeNo = map.get("changeNo").toString();
            List<LinkedHashMap> partNumbers = (List) map.get("partNumbers");
            List<Map<String, Object>> inventorys = (List<Map<String, Object>>) map.get("inventory");
            if (inventorys != null && inventorys.size() > 0) {
                String jsonObject = JSON.toJSONString(inventorys, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                List<RtChangeaffectPartinventoryDO> inventoryDOS = JSON.parseArray(jsonObject, RtChangeaffectPartinventoryDO.class);
                for (LinkedHashMap part : partNumbers) {
                    String number = part.get("number").toString();
                    String type = part.get("type").toString();
                    for (RtChangeaffectPartinventoryDO inventoryDO : inventoryDOS) {
                        String materialcode = inventoryDO.getMaterialcode();
                        if (materialcode.startsWith(number)) {
                            inventoryDO.setCreateBy(user.getDisplayName());
                            inventoryDO.setChangeno(changeNo);
                            inventoryDO.setPartno(number);
                            inventoryDO.setParttype(type);
                        }
                    }
                    long count = rtChangeaffectPartinventoryMapper.count(new RtChangeaffectPartinventoryDO(changeNo, number));
                    if (count > 0) {
                        rtChangeaffectPartinventoryMapper.deleteById(changeNo, number);
                    }
                }
                int i = rtChangeaffectPartinventoryMapper.insertBatch(inventoryDOS);
            }
        }
        return Collections.emptyList();
    }


    @Override
    public List<ContentUploadDTO> batchUploadFile(List<MultipartFile> file, BigInteger workFlowContainerId) {
        JSONObject jsonObject = new JSONObject();
        // BigInteger oid=rtChangeMapper.queryChangeId(workFlowContainerId);
        if (ObjectUtil.isNull(workFlowContainerId)) {
            throw RTErrorCodeEnum.CHANGEINFO_NOT_EXIST.getException("变更单不存在");
        }
        jsonObject.put("oid", workFlowContainerId.toString());
        jsonObject.put("otype", TableTypeConstrant.TY_PJ_CHANGEINFO_OTYPE);
        String uploadStr = jsonObject.toJSONString();
        BatchUploadDTO batchUploadDTO = JSON.parseObject(uploadStr, BatchUploadDTO.class);
        batchUploadDTO.setFileList(file);

        return this.fileHandleService.batchUploadFile(batchUploadDTO);
    }

    /**
     * 查询成品码订单信息
     *
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public List<JSONObject> queryProductOrderList(LinkedHashMap<String, Object> map) throws Exception {
        List<JSONObject> list = new ArrayList<>();
        if (!map.isEmpty()) {
            JSONObject body = new JSONObject();
            String changeNo = map.get("changeNo").toString();
            String partNumber = map.get("partNumber").toString();
            String partType = map.get("partType").toString();
            String type = map.get("type").toString();
            String secNum = map.get("secNum").toString();
            if (RTPlmConstant.PATTERNCODE.equals(partType)){
                body.put("ZTH", partNumber);
            }else if (RTPlmConstant.MATERIALCODE.equals(partType)){
                body.put("MATNR", partNumber);
            }else if (RTPlmConstant.PRODUCTCODE.equals(partType)){
                body.put("MATNR1", partNumber);
            }
            body.put("POTX1", secNum);
            if (StringUtils.isNotBlank(changeNo) && "save".equals(type)) {
                List<RtChangeaffectOrderlistDO> doList = this.rtChangeaffectOrderlistMapper.queryByChangeNoAndPartNumber(changeNo, partNumber, partType, secNum);
                if (CollUtil.isNotEmpty(doList)){
                    List<JSONObject> jsonList = doList.stream().map(item -> (JSONObject) JSONObject.toJSON(item)).collect(Collectors.toList());
                    list.addAll(jsonList);
                }
            }
            if (CollectionUtils.isEmpty(list)) {
                String queryStr = this.commonService.sendPostRequest(queryOrderListUrl, queryOrderListUsername, queryOrderListPassword, body.toString());
                if (StringUtils.isBlank(queryStr)) {
                    throw new Exception("该物料无订单BOM！");
                }
                JSONObject out = JSON.parseObject(queryStr);
                if (out.containsKey("ET_TAB")) {
                    JSONObject OUT_TAB = out.getJSONObject("ET_TAB");
                    if (OUT_TAB == null) {
                        throw new Exception("该物料无订单BOM！");
                    }
                    if (OUT_TAB.containsKey("item")) {
                        JSONArray item = OUT_TAB.getJSONArray("item");
                        for (int i = 0; i < item.size(); i++) {
                            JSONObject itemObject = item.getJSONObject(i);
                            Object WERKS = itemObject.get("WERKS");
                            Object VBELN = itemObject.get("VBELN");
                            Object POSNR = itemObject.get("POSNR");
                            Object MATNR1 = itemObject.get("MATNR1");
                            Object MATNR = itemObject.get("MATNR");
                            Object ZTH = itemObject.get("ZTH");
                            Object MATNR2 = itemObject.get("MATNR2");
                            Object MENGE = itemObject.get("MENGE");
                            Object ZJX = itemObject.get("ZJX");
                            Object KWMENG = itemObject.get("KWMENG");
                            Object KALAB = itemObject.get("KALAB");
                            Object AUFNR = itemObject.get("AUFNR");
                            Object WEMNG = itemObject.get("WEMNG");
                            Object BU_SORT1 = itemObject.get("BU_SORT1");
                            Object GSTRP = itemObject.get("GSTRP");
                            Object GLTRP = itemObject.get("GLTRP");
                            Object ERDAT = itemObject.get("ERDAT");
                            Object ERZET = itemObject.get("ERZET");
                            String potx1 = itemObject.get("POTX1").toString();
                            String duanhao = "";
                            if (StringUtils.isNotBlank(potx1)) {
                                duanhao = potx1.split("|")[0];
                            }
                            itemObject = new JSONObject();
                            itemObject.put("factory", WERKS);
                            itemObject.put("orderno", VBELN);
                            itemObject.put("itemno", POSNR);
                            itemObject.put("powerproductcode", MATNR1);
                            itemObject.put("crewproductcode", MATNR);
                            itemObject.put("secnumber", duanhao);
                            itemObject.put("patterncode", ZTH);
                            itemObject.put("materialcode", MATNR2);
                            itemObject.put("quantity", MENGE);
                            itemObject.put("model", ZJX);
                            itemObject.put("orderquantity", KWMENG);
                            itemObject.put("inventory", KALAB);
                            itemObject.put("ordernumber", AUFNR);
                            itemObject.put("completedquantity", WEMNG);
                            itemObject.put("customer", BU_SORT1);
                            itemObject.put("startDate", GSTRP);
                            itemObject.put("completedDate", GLTRP);
                            itemObject.put("orderCreateDate", ERDAT);
                            itemObject.put("orderCreateTime", ERZET);
                            list.add(itemObject);
                        }
                    }
                }
            }
        }
        return list;
    }

    /**
     * 成品订单保存
     *
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public String saveProductOrderList(LinkedHashMap<String, Object> map) throws Exception {
        StringBuffer sb = new StringBuffer();
        try {
            if (!map.isEmpty()) {
                UserDO user = TyAccountContext.getUser();
                String changeNo = map.get("changeNo").toString();
                String partNumber = map.get("partNumber").toString();
                String partType = map.get("partType").toString();
                String secNum = map.get("secNum").toString();
                List<Map<String, Object>> inventorys = (List<Map<String, Object>>) map.get("orderList");
                if (CollectionUtils.isNotEmpty(inventorys)) {
                    String jsonObject = JSON.toJSONString(inventorys, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                    List<RtChangeaffectOrderlistDO> orderlistDOS = JSON.parseArray(jsonObject, RtChangeaffectOrderlistDO.class);
                    for (RtChangeaffectOrderlistDO orderlistDO : orderlistDOS) {
                        orderlistDO.setCreateby(user.getDisplayName());
                        orderlistDO.setChangeno(changeNo);
                        orderlistDO.setPartnumber(partNumber);
                        orderlistDO.setParttype(partType);
                        orderlistDO.setSecNum(secNum);
                    }
                    long count = rtChangeaffectOrderlistMapper.count(new RtChangeaffectOrderlistDO(changeNo, partNumber, partType, secNum));
                    if (count > 0) {
                        rtChangeaffectOrderlistMapper.deleteById(changeNo, partNumber, partType, secNum);
                    }
                    int i = rtChangeaffectOrderlistMapper.insertBatch(orderlistDOS);
                }
            }
            sb.append("保存成功");
        } catch (Exception e) {
            sb.append("保存失败：" + e.getMessage());
        }
        return sb.toString();
    }

    /**
     * 获取用户所在部门
     *
     * @param oid
     * @return
     * @throws Exception
     */
    @Override
    public String getOrgNameByUserOid(String oid) throws Exception {
        String name = "";
        if (StringUtils.isBlank(oid)) {
            UserDO user = TyAccountContext.getUser();
            oid = String.valueOf(user.getOid());
        }
        if (StringUtils.isNotBlank(oid)) {
            List<OrgDO> list = this.rtChangeMapper.getOrgByUserOid(oid);
            if (list.stream().anyMatch(item -> TableTypeConstrant.TY_ORGCONTAINER_OTYPE.equals(item.getContainerotype()))) {
                OrgDO orgDO = list.stream().filter(item -> TableTypeConstrant.TY_ORGCONTAINER_OTYPE.equals(item.getContainerotype())).collect(Collectors.toList()).get(0);
                name = orgDO.getName();
            } else {
                if (list.stream().anyMatch(item -> TableTypeConstrant.TY_SITECONTAINER_OTYPE.equals(item.getContainerotype()))) {
                    OrgDO orgDO = list.stream().filter(item -> TableTypeConstrant.TY_SITECONTAINER_OTYPE.equals(item.getContainerotype())).collect(Collectors.toList()).get(0);
                    name = orgDO.getName();
                }
            }
        }
        return name;
    }

    /**
     * 获取受影响的MBOM
     *
     * @param reqMap
     * @return
     */
    @Override
    public JSONObject getChangeImpactMbom(LinkedHashMap<String, Object> reqMap) throws Exception {
        JSONObject result = new JSONObject();
        UserDO user = TyAccountContext.getUser();
        if (!reqMap.isEmpty()) {
            List<String> PatternList = new ArrayList<>();
            List<String> MaterialList = new ArrayList<>();
            List<String> StandardList = new ArrayList<>();
            if (reqMap.containsKey("PatternCode")) PatternList = (List<String>) reqMap.get("PatternCode");
            if (reqMap.containsKey("MaterialCode")) MaterialList = (List<String>) reqMap.get("MaterialCode");
            if (reqMap.containsKey("Standard")) StandardList = (List<String>) reqMap.get("Standard");
            String changeNo = (String) reqMap.get("changeNo");
            String changeType = (String) reqMap.get("changeType");
            List<RtChangeaffectFinishedbomDO> productList = new ArrayList();
            List<JSONObject> mbomDOList = new ArrayList();
            List<JSONObject> appointtList = new ArrayList<>();
            List<String> tempList = new ArrayList<>();
            if (StringUtils.isNotBlank(changeNo)) {
                if (CollectionUtils.isNotEmpty(PatternList)) {
                    for (String PatternCode : PatternList) {
                        List<JSONObject> materialList = this.rtChangeMapper.queryPatternOrMaterialCode(PatternCode, "MaterialCode", RTPlmConstant.VIEW_DESIGN);
                        for (JSONObject json : materialList) {
                            String partNumber = json.getString("PARTNUMBER");
                            if (!tempList.contains(partNumber)) {
                                tempList.add(partNumber);
                            }
                        }
                        //获取受影响的成品BOM
                        if (changeNo.contains("RTTJST")) {
                            List<RtChangeaffectFinishedbomDO> tempFinishBoms = rtChangeaffectFinishedbomMapper.queryByChangeNoAndPartNo(changeNo, PatternCode);
                            if (CollectionUtils.isNotEmpty(tempFinishBoms)) {
                                productList.addAll(tempFinishBoms);
                            }
                        }
                        //获取关联变更影响的成品BOM
                        List<RtChangeaffectAssociatedbomDO> associatedbomDOS = rtChangeaffectAssociatedbomMapper.queryByChangeNoAndPartNo(changeNo, PatternCode);
                        if (CollectionUtils.isNotEmpty(associatedbomDOS)) {
                            for (RtChangeaffectAssociatedbomDO associatedbomDO : associatedbomDOS) {
                                String bomType = associatedbomDO.getBomtype();
                                if ("成品码".equals(bomType)) {
                                    RtChangeaffectFinishedbomDO finishedbomDO = new RtChangeaffectFinishedbomDO(associatedbomDO.getChangeno(), associatedbomDO.getPartnumber());
                                    finishedbomDO.setCustomer(associatedbomDO.getCustomerCode());
                                    finishedbomDO.setDevelopmentorder(associatedbomDO.getDevCode());
                                    finishedbomDO.setFinishedproductcode(associatedbomDO.getCode());
                                    finishedbomDO.setFinishedproductcodesstatus(associatedbomDO.getStatus());
                                    finishedbomDO.setFirstParent(associatedbomDO.getFirstParent());
                                    finishedbomDO.setMaterialcode(associatedbomDO.getMaterialCode());
                                    finishedbomDO.setMaterialdescription(associatedbomDO.getMaterialDescription());
                                    finishedbomDO.setModel(associatedbomDO.getProductType());
                                    finishedbomDO.setProductioninvietnam(associatedbomDO.getMadeVietnam());
                                    finishedbomDO.setObjectid(associatedbomDO.getObjectid());
                                    finishedbomDO.setObjecttype(associatedbomDO.getObjecttype());
                                    finishedbomDO.setObjectversion(associatedbomDO.getObjectversion());
                                    finishedbomDO.setSegmentnumber(associatedbomDO.getSegmNum());
                                    finishedbomDO.setStatusrequiretable(associatedbomDO.getStatusRequireCode());
                                    finishedbomDO.setTotalusage(associatedbomDO.getCount());
                                    finishedbomDO.setV2model(associatedbomDO.getV2Model());
                                    finishedbomDO.setParttype(associatedbomDO.getParttype());
                                    productList.add(finishedbomDO);
                                }
                            }
                            ;
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(MaterialList)) {
                    for (String MaterialCode : MaterialList) {
                        if (!tempList.contains(MaterialCode)) {
                            tempList.add(MaterialCode);
                        }
                        //获取成品BOM
                        if (changeNo.contains("RTTJST")) {
                            List<RtChangeaffectFinishedbomDO> tempFinishBoms = rtChangeaffectFinishedbomMapper.queryByChangeNoAndPartNo(changeNo, MaterialCode);
                            if (CollectionUtils.isNotEmpty(tempFinishBoms)) {
                                productList.addAll(tempFinishBoms);
                            }
                        }
                        //获取关联变更影响的成品BOM
                        List<RtChangeaffectAssociatedbomDO> associatedbomDOS = rtChangeaffectAssociatedbomMapper.queryByChangeNoAndPartNo(changeNo, MaterialCode);
                        if (CollectionUtils.isNotEmpty(associatedbomDOS)) {
                            for (RtChangeaffectAssociatedbomDO associatedbomDO : associatedbomDOS) {
                                String bomType = associatedbomDO.getBomtype();
                                if ("成品码".equals(bomType)) {
                                    RtChangeaffectFinishedbomDO finishedbomDO = new RtChangeaffectFinishedbomDO(associatedbomDO.getChangeno(), associatedbomDO.getPartnumber());
                                    finishedbomDO.setCustomer(associatedbomDO.getCustomerCode());
                                    finishedbomDO.setDevelopmentorder(associatedbomDO.getDevCode());
                                    finishedbomDO.setFinishedproductcode(associatedbomDO.getCode());
                                    finishedbomDO.setFinishedproductcodesstatus(associatedbomDO.getStatus());
                                    finishedbomDO.setFirstParent(associatedbomDO.getFirstParent());
                                    finishedbomDO.setMaterialcode(associatedbomDO.getMaterialCode());
                                    finishedbomDO.setMaterialdescription(associatedbomDO.getMaterialDescription());
                                    finishedbomDO.setModel(associatedbomDO.getProductType());
                                    finishedbomDO.setProductioninvietnam(associatedbomDO.getMadeVietnam());
                                    finishedbomDO.setObjectid(associatedbomDO.getObjectid());
                                    finishedbomDO.setObjecttype(associatedbomDO.getObjecttype());
                                    finishedbomDO.setObjectversion(associatedbomDO.getObjectversion());
                                    finishedbomDO.setSegmentnumber(associatedbomDO.getSegmNum());
                                    finishedbomDO.setStatusrequiretable(associatedbomDO.getStatusRequireCode());
                                    finishedbomDO.setTotalusage(associatedbomDO.getCount());
                                    finishedbomDO.setV2model(associatedbomDO.getV2Model());
                                    finishedbomDO.setParttype(associatedbomDO.getParttype());
                                    productList.add(finishedbomDO);
                                }
                            }
                            ;
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(StandardList)) {
                    for (String MaterialCode : StandardList) {
                        if (!tempList.contains(MaterialCode)) {
                            tempList.add(MaterialCode);
                        }
                        //获取成品BOM
                        if (changeNo.contains("RTTJST")) {
                            List<RtChangeaffectFinishedbomDO> tempFinishBoms = rtChangeaffectFinishedbomMapper.queryByChangeNoAndPartNo(changeNo, MaterialCode);
                            if (CollectionUtils.isNotEmpty(tempFinishBoms)) {
                                productList.addAll(tempFinishBoms);
                            }
                        }
                        //获取关联变更影响的成品BOM
                        List<RtChangeaffectAssociatedbomDO> associatedbomDOS = rtChangeaffectAssociatedbomMapper.queryByChangeNoAndPartNo(changeNo, MaterialCode);
                        if (CollectionUtils.isNotEmpty(associatedbomDOS)) {
                            for (RtChangeaffectAssociatedbomDO associatedbomDO : associatedbomDOS) {
                                String bomType = associatedbomDO.getBomtype();
                                if ("成品码".equals(bomType)) {
                                    RtChangeaffectFinishedbomDO finishedbomDO = new RtChangeaffectFinishedbomDO(associatedbomDO.getChangeno(), associatedbomDO.getPartnumber());
                                    finishedbomDO.setCustomer(associatedbomDO.getCustomerCode());
                                    finishedbomDO.setDevelopmentorder(associatedbomDO.getDevCode());
                                    finishedbomDO.setFinishedproductcode(associatedbomDO.getCode());
                                    finishedbomDO.setFinishedproductcodesstatus(associatedbomDO.getStatus());
                                    finishedbomDO.setFirstParent(associatedbomDO.getFirstParent());
                                    finishedbomDO.setMaterialcode(associatedbomDO.getMaterialCode());
                                    finishedbomDO.setMaterialdescription(associatedbomDO.getMaterialDescription());
                                    finishedbomDO.setModel(associatedbomDO.getProductType());
                                    finishedbomDO.setProductioninvietnam(associatedbomDO.getMadeVietnam());
                                    finishedbomDO.setObjectid(associatedbomDO.getObjectid());
                                    finishedbomDO.setObjecttype(associatedbomDO.getObjecttype());
                                    finishedbomDO.setObjectversion(associatedbomDO.getObjectversion());
                                    finishedbomDO.setSegmentnumber(associatedbomDO.getSegmNum());
                                    finishedbomDO.setStatusrequiretable(associatedbomDO.getStatusRequireCode());
                                    finishedbomDO.setTotalusage(associatedbomDO.getCount());
                                    finishedbomDO.setV2model(associatedbomDO.getV2Model());
                                    finishedbomDO.setParttype(associatedbomDO.getParttype());
                                    productList.add(finishedbomDO);
                                }
                            }
                            ;
                        }
                    }
                }
                for (String number : tempList) {
                    //获取所有工厂视图
                    if (StringUtils.isNotBlank(factoryView)) {
                        String[] factoryArr = factoryView.split(",");
                        for (String factory : factoryArr) {
                            //获取指定信息
                            appointtList = queryAppointtList(appointtList, number, "MaterialCode", factory);
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(productList)) {
                    for (RtChangeaffectFinishedbomDO finishedbomDO : productList) {
                        String productCode = finishedbomDO.getFinishedproductcode();
                        String devCode = finishedbomDO.getDevelopmentorder();
                        String materialCode = finishedbomDO.getMaterialcode();
                        if (StringUtils.isNotBlank(productCode) && StringUtils.isNotBlank(devCode) && StringUtils.isNotBlank(materialCode)) {
                            if (devCode.startsWith("Z")) {
                                //获取所有工厂视图
                                if (StringUtils.isNotBlank(factoryView)) {
                                    String[] factoryArr = factoryView.split(",");
                                    for (String factory : factoryArr) {
                                        //判断是否存在该视图的物料
                                        List<JSONObject> materialList = this.rtChangeMapper.queryMaterialCode(materialCode, "", factory);
                                        if (CollectionUtils.isNotEmpty(materialList)) {
                                            if ("增加".equals(changeType) || "删除".equals(changeType)) {
                                                JSONObject mbomJson = coverMbom(finishedbomDO, user);
                                                mbomJson.put("factory", factory);
                                                mbomJson.put("mbom", productCode);
                                                mbomJson.put("isAdjust", "否");
                                                mbomDOList.add(mbomJson);
                                            } else if ("修改".equals(changeType)) {
                                                //判断是否存在父子关系
                                                List<JSONObject> releationList = this.rtChangeMapper.judgeChildAndParentRelation(productCode, materialCode, factory);
                                                if (CollectionUtils.isNotEmpty(releationList)) {
                                                    //存在父子关系
                                                    JSONObject mbomJson = coverMbom(finishedbomDO, user);
                                                    mbomJson.put("factory", factory);
                                                    mbomJson.put("mbom", productCode);
                                                    mbomJson.put("isAdjust", "否");
                                                    mbomDOList.add(mbomJson);
                                                } else {
                                                    //不存在父子关系，物料有可能调整到了机组下，查找机组成品码
                                                    List<JSONObject> parentList = this.rtChangeMapper.queryParentPartByType(productCode, "ProductCode", factory);
                                                    if (CollectionUtils.isNotEmpty(parentList)) {
                                                        String parentNumber = parentList.get(0).getString("PARTNUMBER");
                                                        //判断是机组成品码与物料码否存在父子关系
                                                        releationList = this.rtChangeMapper.judgeChildAndParentRelation(parentNumber, materialCode, factory);
                                                        if (CollectionUtils.isNotEmpty(releationList)) {
                                                            //存在父子关系
                                                            JSONObject mbomJson = coverMbom(finishedbomDO, user);
                                                            mbomJson.put("factory", factory);
                                                            mbomJson.put("mbom", parentNumber);
                                                            mbomJson.put("isAdjust", "是");
                                                            mbomDOList.add(mbomJson);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                //当前是机组成品码
                                //获取所有工厂视图
                                if (StringUtils.isNotBlank(factoryView)) {
                                    String[] factoryArr = factoryView.split(",");
                                    for (String factory : factoryArr) {
                                        //判断是否存在该视图的物料
                                        List<JSONObject> materialList = this.rtChangeMapper.queryMaterialCode(materialCode, "", factory);
                                        if (CollectionUtils.isNotEmpty(materialList)) {
                                            if ("增加".equals(changeType) || "删除".equals(changeType)) {
                                                JSONObject mbomJson = coverMbom(finishedbomDO, user);
                                                mbomJson.put("factory", factory);
                                                mbomJson.put("mbom", productCode);
                                                mbomJson.put("isAdjust", "否");
                                                mbomDOList.add(mbomJson);
                                            } else if ("修改".equals(changeType)) {
                                                //判断是否存在父子关系
                                                List<JSONObject> releationList = this.rtChangeMapper.judgeChildAndParentRelation(productCode, materialCode, factory);
                                                if (CollectionUtils.isNotEmpty(releationList)) {
                                                    //存在父子关系
                                                    JSONObject mbomJson = coverMbom(finishedbomDO, user);
                                                    mbomJson.put("factory", factory);
                                                    mbomJson.put("mbom", productCode);
                                                    mbomJson.put("isAdjust", "否");
                                                    mbomDOList.add(mbomJson);
                                                } else {
                                                    //不存在父子关系，物料有可能调整到了动力下，查找动力成品码
                                                    List<PartMasterDO> parentList = this.rtChangeMapper.getChildProductCode(productCode, "ProductCode", factory);
                                                    if (CollectionUtils.isNotEmpty(parentList)) {
                                                        String parentNumber = parentList.get(0).getPartnumber();
                                                        //判断是动力成品码与物料码否存在父子关系
                                                        releationList = this.rtChangeMapper.judgeChildAndParentRelation(parentNumber, materialCode, factory);
                                                        if (CollectionUtils.isNotEmpty(releationList)) {
                                                            //存在父子关系
                                                            JSONObject mbomJson = coverMbom(finishedbomDO, user);
                                                            mbomJson.put("factory", factory);
                                                            mbomJson.put("mbom", parentNumber);
                                                            mbomJson.put("isAdjust", "是");
                                                            mbomDOList.add(mbomJson);
                                                        }
                                                    }
                                                }
                                            } else if ("图号升级".equals(changeType)) {
                                                JSONObject mbomJson = coverMbom(finishedbomDO, user);
                                                mbomJson.put("factory", factory);
                                                mbomJson.put("mbom", productCode);
                                                mbomJson.put("isAdjust", "否");
                                                mbomDOList.add(mbomJson);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            result.put("appoint", appointtList);
            result.put("mbom", mbomDOList);
        }
        return result;
    }

    /**
     * 保存受影响的MBOM
     *
     * @param map
     * @return
     */
    @Override
    public String saveChangeImpactMbom(LinkedHashMap<String, Object> map) throws Exception {
        UserDO user = TyAccountContext.getUser();
        String changeNo = map.get("changeNo").toString();
        String partnumber = map.get("partNumber").toString();
        if (map != null && StringUtils.isNotBlank(changeNo) && StringUtils.isNotBlank(partnumber)) {
            List<Map<String, Object>> appoints = (List<Map<String, Object>>) map.get("appoint");
            List<Map<String, Object>> mboms = (List<Map<String, Object>>) map.get("mbom");
            if (appoints != null && appoints.size() > 0) {
                String jsonObject = JSON.toJSONString(appoints, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                List<RtChangeaffectAppointDO> appointDOS = JSON.parseArray(jsonObject, RtChangeaffectAppointDO.class);
                for (RtChangeaffectAppointDO appointDO : appointDOS) {
                    appointDO.setCreateBy(user.getDisplayName());
                    appointDO.setChangeno(changeNo);
                    appointDO.setPartnumber(partnumber);
                    appointDO.setType("制造");
                }
                long count = rtChangeaffectAppointMapper.count(new RtChangeaffectAppointDO(changeNo, partnumber, "制造"));
                if (count > 0) {
                    rtChangeaffectAppointMapper.deleteById(changeNo, partnumber, "制造");
                }
                int i = rtChangeaffectAppointMapper.insertBatch(appointDOS);
            }

            if (mboms != null && mboms.size() > 0) {
                String jsonObject = JSON.toJSONString(mboms, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                List<RtChangeaffectMbomDO> mbomDOS = JSON.parseArray(jsonObject, RtChangeaffectMbomDO.class);
                for (RtChangeaffectMbomDO mbomDO : mbomDOS) {
                    long count = rtChangeaffectMbomMapper.count(new RtChangeaffectMbomDO(mbomDO.getChangeno(), mbomDO.getPartnumber()));
                    if (count > 0) {
                        rtChangeaffectMbomMapper.deleteById(mbomDO.getChangeno().toString(), mbomDO.getPartnumber().toString());
                    }
                }
                int i = rtChangeaffectMbomMapper.insertBatch(mbomDOS);
            }
        }
        return "保存成功";
    }

    /**
     * 获取已保存受影响的MBOM
     *
     * @param reqMap
     * @return
     */
    @Override
    public JSONObject getSaveChangeImpactMbom(LinkedHashMap<String, Object> reqMap) throws Exception {
        JSONObject result = new JSONObject();
        UserDO user = TyAccountContext.getUser();
        if (!reqMap.isEmpty()) {
            List<String> PatternList = new ArrayList<>();
            List<String> MaterialList = new ArrayList<>();
            List<String> StandardList = new ArrayList<>();
            if (reqMap.containsKey("PatternCode")) PatternList = (List<String>) reqMap.get("PatternCode");
            if (reqMap.containsKey("MaterialCode")) MaterialList = (List<String>) reqMap.get("MaterialCode");
            if (reqMap.containsKey("Standard")) StandardList = (List<String>) reqMap.get("Standard");
            PatternList.addAll(MaterialList);
            PatternList.addAll(StandardList);
            String changeNo = (String) reqMap.get("changeNo");
            List<RtChangeaffectFinishedbomDO> productList = new ArrayList();
            List<RtChangeaffectMbomDO> mbomDOList = new ArrayList<>();
            List<RtChangeaffectAppointDO> appointtList = new ArrayList<>();
            List<String> tempList = new ArrayList<>();
            if (StringUtils.isNotBlank(changeNo)) {
                for (String code : PatternList) {
                    List<RtChangeaffectMbomDO> mbomDOS = this.rtChangeaffectMbomMapper.queryByChangeNoAndPartNo(changeNo, code);
                    List<RtChangeaffectAppointDO> appointDOS = this.rtChangeaffectAppointMapper.queryByChangeNoAndPartNo(changeNo, code, "制造");
                    if (CollectionUtils.isNotEmpty(mbomDOS)) {
                        mbomDOList.addAll(mbomDOS);
                    }
                    if (CollectionUtils.isNotEmpty(appointDOS)) {
                        appointtList.addAll(appointDOS);
                    }
                }
            }
            result.put("appoint", appointtList);
            result.put("mbom", mbomDOList);
        }
        return result;
    }

    /**
     * 锁定成品码下单
     *
     * @param reqMap
     * @return
     */
    @Override
    public String lockProductOrder(LinkedHashMap<String, Object> reqMap) {
        String type = "";
        if (reqMap != null) {
            UserDO user = TyAccountContext.getUser();
            type = reqMap.get("type").toString();
            if (StringUtils.isBlank(type)) {
                throw new RuntimeException("参数type为空");
            }
            String changeNo = reqMap.get("changeNo").toString();
            if (StringUtils.isBlank(changeNo)) {
                throw new RuntimeException("参数changeNo为空");
            }
            String partNumber = reqMap.get("partNumber").toString();
            if (StringUtils.isBlank(partNumber)) {
                throw new RuntimeException("参数partNumber为空");
            }
            List<Map<String, Object>> prodcutList = (List<Map<String, Object>>) reqMap.get("prodcutList");
            if (CollectionUtils.isEmpty(prodcutList)) {
                throw new RuntimeException("没有需要保存的数据");
            }
            String jsonObject = JSON.toJSONString(prodcutList, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
            List<RtChangeLockInfoDO> lockInfoDOS = JSON.parseArray(jsonObject, RtChangeLockInfoDO.class);
            if ("save".equals(type)) {
                type = "保存";
                if (CollectionUtils.isNotEmpty(lockInfoDOS)) {
                    for (RtChangeLockInfoDO linkInfo : lockInfoDOS) {
                        linkInfo.setChangeNo(changeNo);
                        linkInfo.setPartNumber(partNumber);
                        linkInfo.setIsLock("0");
                        linkInfo.setCreater(user.getDisplayName());
                        linkInfo.setCreateTime(new Date());
                        long count = rtChangeLockInfoMapper.count(linkInfo);
                        if (count > 0) {
                            rtChangeLockInfoMapper.deleteBy(linkInfo);
                        }
                    }
                    int i = rtChangeLockInfoMapper.insertBatch(lockInfoDOS);
                }
            } else if ("lock".equals(type)) {
                type = "锁定";
                if (CollectionUtils.isNotEmpty(lockInfoDOS)) {
                    for (RtChangeLockInfoDO linkInfo : lockInfoDOS) {
                        linkInfo.setChangeNo(changeNo);
                        linkInfo.setPartNumber(partNumber);
                        linkInfo.setIsLock("2");
                        linkInfo.setLocker(user.getDisplayName());
                        linkInfo.setLockTime(new Date());
                        long count = rtChangeLockInfoMapper.count(linkInfo);
                        if (count > 0) {
                            rtChangeLockInfoMapper.updateBy(linkInfo);
                        } else {
                            rtChangeLockInfoMapper.insert(linkInfo);
                        }
                    }
                }
            } else if ("unlock".equals(type)) {
                type = "解锁";
                if (CollectionUtils.isNotEmpty(lockInfoDOS)) {
                    for (RtChangeLockInfoDO linkInfo : lockInfoDOS) {
                        linkInfo.setChangeNo(changeNo);
                        linkInfo.setPartNumber(partNumber);
                        linkInfo.setIsLock("1");
                        linkInfo.setUnLocker(user.getDisplayName());
                        linkInfo.setUnLockTime(new Date());
                        long count = rtChangeLockInfoMapper.count(linkInfo);
                        if (count > 0) {
                            rtChangeLockInfoMapper.updateBy(linkInfo);
                        } else {
                            rtChangeLockInfoMapper.insert(linkInfo);
                        }
                    }
                }
            }
        }
        return type + "成功！";
    }

    /**
     * 解锁成品码下单
     *
     * @param
     * @return
     */
    @Override
    public List<RtChangeLockInfoDO> getLockProductOrder(String changeNo, String partNumber, String productCode) {
        RtChangeLockInfoDO lockInfoDO = new RtChangeLockInfoDO();
        lockInfoDO.setChangeNo(changeNo);
        lockInfoDO.setPartNumber(partNumber);
        lockInfoDO.setProductCode(productCode);
        return rtChangeLockInfoMapper.queryInfoByDO(lockInfoDO);
    }

    /**
     * 查询成品码状态
     *
     * @param list
     * @return
     * @throws Exception
     */
    @Override
    public List<JSONObject> queryProductCodeStatus(List<JSONObject> list) throws Exception {
        List<JSONObject> result = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        StringBuffer error1 = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            JSONObject json = list.get(i);
            String code = json.get("code").toString();
            String factory = json.get("factory").toString();
            if (StringUtils.isNotBlank(factory) && StringUtils.isNotBlank(code)) {
                PartDO partDO = this.rtPartMapper.queryLatestPartByNumberAndView(code, factory, null);
                if (partDO != null) {
                    String status = partDO.getLifecyclestagekey();
                    JSONObject jsonObject = new JSONObject();
                    if (StringUtils.isNotBlank(productUnlockStatus)) {
                        if (productUnlockStatus.contains(status)) {
                            jsonObject.put("lock", false);
                        } else {
                            jsonObject.put("lock", true);
                        }
                    }
                    jsonObject.put("factory", factory);
                    jsonObject.put("code", code);
                    result.add(jsonObject);
                } else {
                    if (StringUtils.isNotBlank(error1.toString())) {
                        error1.append("；");
                    }
                    error1.append(code);
                }
            }
        }
        if (StringUtils.isNotBlank(error1.toString())) {
            throw new Exception("以下编码不存在：\r\n" + error1.toString());
        }
        return result;
    }

    private List<Map<String, PartDetailsVO>> queryChildPart(List<Map<String, PartDetailsVO>> list, String oid, String otype) {
        if (StringUtils.isNotBlank(oid) && StringUtils.isNotBlank(otype)) {
            PartDetailsVO parentDetailVO = this.typlmPartService.queryPartDetails(new BigInteger(oid), otype);
            List<PartDO> partDOS = this.rtChangeMapper.queryChildPart(oid, RTPlmConstant.VIEW_DESIGN);
            for (PartDO partDO : partDOS) {
                Map<String, PartDetailsVO> map = new HashMap<>();
                map.put("parent", parentDetailVO);
                BigInteger childOid = partDO.getOid();
                String childOType = partDO.getOtype();
                PartDetailsVO detailsVO = this.typlmPartService.queryPartDetails(childOid, childOType);
                map.put("child", detailsVO);
                list.add(map);
                //                queryChildPart(list, childOid.toString(), childOType);
            }
        }
        return list;
    }

    //重新组装MbomDO数据
    private JSONObject coverMbom(RtChangeaffectFinishedbomDO finishedbomDO, UserDO user) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("changeNo", finishedbomDO.getChangeno() == null ? "" : finishedbomDO.getChangeno());
        jsonObject.put("partNumber", finishedbomDO.getPartnumber() == null ? "" : finishedbomDO.getPartnumber());
        jsonObject.put("firstParent", finishedbomDO.getFirstParent() == null ? "" : finishedbomDO.getFirstParent());
        jsonObject.put("DevelopmentOrder", finishedbomDO.getDevelopmentorder() == null ? "" : finishedbomDO.getDevelopmentorder());
        jsonObject.put("model", finishedbomDO.getModel() == null ? "" : finishedbomDO.getModel());
        jsonObject.put("v2model", finishedbomDO.getV2model() == null ? "" : finishedbomDO.getV2model());
        jsonObject.put("FinishedProductCode", finishedbomDO.getFinishedproductcode() == null ? "" : finishedbomDO.getFinishedproductcode());
        jsonObject.put("objectid", finishedbomDO.getObjectid());
        jsonObject.put("objecttype", finishedbomDO.getObjecttype());
        jsonObject.put("objectversion", finishedbomDO.getObjectversion());
        jsonObject.put("materialCode", finishedbomDO.getMaterialcode() == null ? "" : finishedbomDO.getMaterialcode());
        jsonObject.put("TotalUsage", finishedbomDO.getTotalusage() == null ? "" : finishedbomDO.getTotalusage());
        jsonObject.put("segmentNumber", finishedbomDO.getSegmentnumber() == null ? "" : finishedbomDO.getSegmentnumber());
        jsonObject.put("MaterialDescription", finishedbomDO.getMaterialdescription() == null ? "" : finishedbomDO.getMaterialdescription());
        jsonObject.put("ProductioninVietnam", finishedbomDO.getProductioninvietnam() == null ? "" : finishedbomDO.getProductioninvietnam());
        jsonObject.put("StatusRequireTable", finishedbomDO.getStatusrequiretable() == null ? "" : finishedbomDO.getStatusrequiretable());
        jsonObject.put("FinishedProductCodesStatus", finishedbomDO.getFinishedproductcodesstatus());
        jsonObject.put("customer", finishedbomDO.getCustomer() == null ? "" : finishedbomDO.getCustomer());
        jsonObject.put("createBy", user.getDisplayName());
        jsonObject.put("parttype", finishedbomDO.getParttype() == null ? "" : finishedbomDO.getParttype());
        return jsonObject;
    }

    //获取所有指定信息
    private List queryAppointtList(List list, String partNumber, String type, String factory) throws Exception {
        List<RtZdMxbDO> appointdetailList = rtZdMapper.selectMxbByPartAndFactory(partNumber, factory);
        for (int j = 0; j < appointdetailList.size(); j++) {
            RtZdMxbDO appointdetailDO = appointdetailList.get(j);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("customerCode", appointdetailDO.getCustomerCode() == null ? "" : appointdetailDO.getCustomerCode());
            jsonObject.put("CustomerName", appointdetailDO.getCustomerName() == null ? "" : appointdetailDO.getCustomerName());
            jsonObject.put("DevelopmentOrder", appointdetailDO.getDevCode() == null ? "" : appointdetailDO.getDevCode());
            jsonObject.put("model", appointdetailDO.getProductType() == null ? "" : appointdetailDO.getProductType());
            jsonObject.put("materialCode", appointdetailDO.getMaterialCode() == null ? "" : appointdetailDO.getMaterialCode());
            jsonObject.put("MaterialName", appointdetailDO.getPartName() == null ? "" : appointdetailDO.getPartName());
            jsonObject.put("supplierCode", appointdetailDO.getSupplierCode() == null ? "" : appointdetailDO.getSupplierCode());
            jsonObject.put("SupplierName", appointdetailDO.getSupplierName() == null ? "" : appointdetailDO.getSupplierName());
            jsonObject.put("OrderNo", appointdetailDO.getOrderNo() == null ? "" : appointdetailDO.getOrderNo());
            jsonObject.put("OrderItemNumber", appointdetailDO.getOrderItemNo() == null ? "" : appointdetailDO.getOrderItemNo());
            jsonObject.put("SpecifyType", appointdetailDO.getAppointType() == null ? "" : appointdetailDO.getAppointType());
            list.add(jsonObject);
        }
        return list;
    }
}